package com.dailyplanner.mail.logic;

import java.util.Properties;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.dailyplanner.mail.config.MailConfiguration;
import com.globallogic.dailyplanner.dto.Mail;
import com.globallogic.dailyplanner.dto.MailStatusEnum;

@Stateless
public class MailSender {
	private static final String USERNAME = "mail.auth.username";
	private static final String PASSWORD = "mail.auth.password";
	
	@EJB
	private MailConfiguration mailConfiguration;
	
	public MailStatusEnum sendMessage(String email, Mail mail) {
		final Properties props = mailConfiguration.getMaProperties();
		
		Session session = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(props.getProperty(USERNAME), props.getProperty(PASSWORD));
			}
		});
		
		MimeMessage message = new MimeMessage(session);
		try {
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
			message.setSubject(mail.getSubject());
			message.setText(mail.getBody(), "utf-8", "html");
			Transport.send(message);
		} catch (MessagingException e) {
			return MailStatusEnum.ERROR;
		}
		
		return MailStatusEnum.SUCCESS;
	}
	
}
